<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Admin\StoreGoodsViewPermissions;
use App\Models\Api\Ad;
use App\Models\Api\Area;
use App\Models\Api\Goods;
use App\Models\Api\GoodsStore;
use App\Models\Api\Store;
use App\Tools\ApiService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class IndexController extends Controller
{

    protected $userArr;
    protected $requestArr;
    protected $requestFile;

    public function __construct(Request $request)
    {
        # 获取POST数据
        $this->requestArr = $request->input();
        # 获取file
        $this->requestFile = $request->file();
        # App登录信息判断
        $token = $request->header('token');
        if ($token) {
            $tokenStr = Redis::get("XCX_TOKEN:{$token}");
            if ($tokenStr) {
                Redis::EXPIRE("XCX_TOKEN:{$token}", 86400 * 30);
                $this->userArr = json_decode($tokenStr, true);
            }
        }
    }

    /**
     * 首页接口
     */
    public function index()
    {
        $store_id = $this->userArr['store_id'];
        $info['banner'] = Ad::getListByCateId(2);
        $info['promotion'] = [];
        if ($store_id) {
            $is_agent = Store::where(['id' => $store_id])->value('is_agent');
            if ($is_agent == 0) {
                $good_per = StoreGoodsViewPermissions::where('store_id', $store_id)->value('goods_ids');
                $good_ids = explode(',', $good_per);
                $list = Goods::from('goods as g')
                    ->select(['g.id', 'g.goods_sn', 'g.goods_name', 'g.goods_price', 'g.mini_quantity', 'g.is_group', 'g.goods_img', 'c.cate_name'])
                    ->leftJoin('goods_category as c', 'c.id', '=', 'g.cate_id')
                    ->where(['g.status' => 1, 'g.promotion' => 1])
                    ->whereIn('g.id', $good_ids)
                    ->orderBy('g.id', 'desc')->limit(8)->get();
                foreach ($list as $kk => $vv) {
                    $list[$kk]['goods_id'] = $vv['id'];
                    $list[$kk]['sale_price'] = $vv['goods_price'];
                }
                $info['promotion'] = $list;
            }

        }
        successMsg($info);
    }

    /**
     * 获取地区数据
     */
    public function getArea()
    {
        $id = $this->requestArr['id'] ?: 0;
        $type = $this->requestArr['type'] ?: 0;
        $where['pid'] = $id;
        if ($id > 0) {
            switch ($type) {
                case 1:
                    $where['level'] = 1;
                    $where['pid'] = 0;
                    break;
                case 2:
                    $where['level'] = 2;
                    break;
                case 3:
                    $where['level'] = 3;
                    break;
                default:
                    $where['level'] = 1;
                    $where['pid'] = 0;
                    break;
            }
        }
        $list = Area::getList($where);
        successMsg($list);
    }

    /**
     * 获取地址js
     */
    public function getAreaJs()
    {
        $type = $this->requestArr['type'] ?: 0;
        successMsg();
    }

    /**
     * 获取单品详情
     */
    public function getSingleGoodsInfo()
    {
        $storeId = $this->userArr['store_id'];
        $goodsId = $this->requestArr['goods_id'];
        if ($goodsId) {
            if ($storeId) {
                // 代发
                $is_agent = Store::where(['id' => $storeId])->value('is_agent');
                $where = ['goods_id' => $goodsId, 'store_id' => $storeId];
                $info = GoodsStore::getInfo($where);
                if ($info) {
                    $info['mini_quantity'] = $is_agent == 1 ? 1 : $info['mini_quantity'];
                    $info['goods_img_list'] = json_decode($info['goods_img_list'], true);
                    successMsg($info);
                } else {
                    errorMsg("商品已下架");
                }
            } else {
                $info = Goods::getAInfoById($goodsId);
                successMsg($info);
            }
        }
        errorMsg();
    }

    /**
     * 获取组合商品详情
     */
    public function getMultipleGoodsInfo()
    {
        $storeId = $this->userArr['store_id'];
        $goodsId = $this->requestArr['goods_id'];
        if ($goodsId) {
            if ($storeId) {
                // 代发
                $is_agent = Store::where(['id' => $storeId])->value('is_agent');
                $where = ['goods_id' => $goodsId, 'store_id' => $storeId];
                $info = GoodsStore::getInfo($where);
                if ($info) {
                    $info['mini_quantity'] = $is_agent == 1 ? 1 : $info['mini_quantity'];
                    unset($info['goods_price']);
                    unset($info['sale_price']);
                    unset($info['buy_num']);
                    unset($info['get_num']);
                    $info['goods_group'] = json_decode($info['goods_group'], true);
                    $info['goods_img_list'] = json_decode($info['goods_img_list'], true);
                    $goodsIds = array_column($info['goods_group'], 'id');

                    $goods = GoodsStore::from('goods_store as gs')
                        ->where(['gs.store_id' => $storeId])
                        ->whereIn('gs.goods_id', $goodsIds)
                        ->select('g.id', 'g.goods_price', 'g.goods_name', 'g.goods_img', 'gs.sale_price')
                        ->leftJoin('goods as g', 'g.id', '=', 'gs.goods_id')
                        ->get()
                        ->toArray();
                    if (count($goods) < count($goodsIds)) {
                        errorMsg("未获取到此组合商品中的单品代理权" . count($goods) . count($goodsIds));
                    }
                    foreach ($info['goods_group'] as $key => &$val) {
                        foreach ($goods as $k => $v) {
                            if ($val['id'] == $v['id']) {
                                $val['goods_price'] = $v['goods_price'];
                                $val['goods_name'] = $v['goods_name'];
                                $val['goods_img'] = $v['goods_img'];
                                $val['sale_price'] = $v['sale_price'];
                            }
                        }
                    }
                    successMsg($info);
                } else {
                    errorMsg("商品已下架");
                }
            } else {
                $info = Goods::getAInfoById($goodsId);
                if ($info) {
                    $info['goods_group'] = json_decode($info['goods_group'], true);
                    $goodsIds = array_column($info['goods_group'], 'id');
                    $goods = Goods::getListByIds($goodsIds);
                    foreach ($info['goods_group'] as $key => &$val) {
                        foreach ($goods as $k => $v) {
                            if ($val['id'] == $v['id']) {
                                $val['goods_price'] = $v['goods_price'];
                                $val['goods_name'] = $v['goods_name'];
                                $val['goods_img'] = $v['goods_img'];
                                $val['sale_price'] = $v['sale_price'];
                            }
                        }
                    }
                    successMsg($info);
                }
            }
        }
        errorMsg();
    }
}
